package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.CheckItem;
import com.itheima.pojo.Member;
import com.itheima.pojo.Setmeal;
import com.itheima.service.MemberProfileService;
import com.itheima.service.MemberService;
import com.itheima.service.SetmealService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import java.util.stream.Stream;

/**
 * @author Ning
 * @date 2020/8/21 11:55
 */
@RestController
@RequestMapping(path = "/MemberProfile")
public class MemberProfileController {


    @Reference
    private MemberProfileService memberProfileService;

    @Reference
    MemberService memberService;

    @Reference
    SetmealService setmealService;


    /**
     * 新增会员数据
     * @param member
     * @return
     */
    @RequestMapping(path = "/add")
    public  Result add(@RequestBody   Member member){
        try {
            memberProfileService.add(member);
            return new Result(true,MessageConstant.Query_Member_item_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.Query_Member_item_FAIL);
        }

    }

    /**
     * 分页查询会员档案数据
     * @return
     */
    @RequestMapping(path = "/findPage")
    public Result  findPage(QueryPageBean  queryPageBean){
        try {
            //成功
            PageResult page = memberProfileService.pageQuery(queryPageBean);
            return new Result(true, MessageConstant.Query_Mmber_Qrofile_SUCCESS,page);
        } catch (Exception e) {
            //失败
            e.printStackTrace();
            return  new Result(false,MessageConstant.Query_Mmber_Qrofile_FAIL);
        }
}

    /**
     *
     * @param id
     * @return
     */
    @DeleteMapping(path = "/{id}")
    public  Result deleteById(@PathVariable Integer id){
    try {
        // 删除
        memberProfileService.deleteById(id);
        return new Result(true,MessageConstant.DELETE_Member_item_SUCCESS);
    } catch (RuntimeException e) {
        return new Result(false, e.getMessage());
    } catch (Exception e) {
        return new Result(false,MessageConstant.DELETE_Member_item_FAIL);
    }

}
    @GetMapping(path = "/{id}")
public Result findById(@PathVariable int id){
    try {
        // 查询检查项
        Member member = memberProfileService.findById(id);
        return new Result(true,MessageConstant.QUERY_Member_item_SUCCESS,member);
    } catch (Exception e) {
        e.printStackTrace();
        return new Result(false,MessageConstant.QUERY_Member_item_FAIL);
    }
}

    @PutMapping(path = "/edit")
    public Result edit(@RequestBody Member member){
        try {
            memberProfileService.edit(member);
            return new Result(true, MessageConstant.EDIT_Member_item_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_Member_item_FAIL);
        }
    }

    /**
     * 导出会员数据
     */

    @GetMapping("/export")
    public Result export(Integer[] memberIds,HttpServletResponse response){

        try{
            //导入工作簿
            XSSFWorkbook workbook = new XSSFWorkbook();
            //获取表格文件
            workbook.createSheet("会员档案");
            XSSFSheet sheet = workbook.getSheetAt(0);

            sheet.createRow(0);
            XSSFRow row_0 = sheet.getRow(0);
            row_0.createCell(0).setCellValue("姓名");
            row_0.createCell(1).setCellValue("性别");
            row_0.createCell(2).setCellValue("手机号");
            row_0.createCell(3).setCellValue("套餐名称");
            row_0.createCell(4).setCellValue("检查组");
            row_0.createCell(5).setCellValue("检查项");

            if (memberIds!=null&&memberIds.length>0){

                for (int i = 0; i <memberIds.length ; i++) {

                    Member member = memberService.findById(memberIds[i]);
                    List<Setmeal> setmeals = setmealService.findByMemberId(memberIds[i]);

                    sheet.createRow(i+1);
                    XSSFRow row = sheet.getRow(i+1);

                    row.createCell(0).setCellValue(member.getName());
                    row.createCell(1).setCellValue(member.getSex()=="1"?"男":"女");
                    row.createCell(2).setCellValue(member.getPhoneNumber());

                    if (setmeals==null||setmeals.size()==0){
                        row.createCell(3).setCellValue("[]");
                        row.createCell(4).setCellValue("[]");
                        row.createCell(5).setCellValue("[]");

                    }else {
                        row.createCell(3).setCellValue(setmeals.get(0).getName());

                        if (setmeals.get(0).getCheckGroups()!=null&&setmeals.get(0).getCheckGroups().size()>0){
                            String checkGroupNames="[";
                            for (CheckGroup checkGroup : setmeals.get(0).getCheckGroups()) {
                                checkGroupNames+=checkGroup.getName();
                            }
                            checkGroupNames+="]";
                            row.createCell(4).setCellValue(checkGroupNames);

                            List<CheckItem> checkItems=setmeals.get(0).getCheckGroups().get(0).getCheckItems();
                            if (checkItems!=null&&checkItems.size()>0){

                                String checkItemNames="[";
                                for (CheckItem checkItem :checkItems) {
                                    checkItemNames+=checkItem.getName();
                                }
                                checkItemNames+="]";
                                row.createCell(5).setCellValue(checkItemNames);
                            }else{
                                row.createCell(5).setCellValue("[]");
                            }
                        }else {
                            row.createCell(4).setCellValue("[]");
                            row.createCell(5).setCellValue("[]");
                        }
                    }
                }
            }

            System.out.println("      workbook            "+workbook.getSheetAt(0).getRow(0).getCell(0).getStringCellValue());

            ServletOutputStream out = response.getOutputStream();
            response.setHeader("Content-Disposition", "attachment;filename=report.xlsx");
            workbook.write(out);

            out.flush();
            out.close();
            workbook.close();

            return  new Result(true,MessageConstant.export_MEMBER_SUCCESS);

        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.export_MEMBER_FAIL);

        }



    }

}

